<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\WorkContact\Logic\IndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 客户列表.
 *
 * Class Index
 * @Controller
 */
class Export extends AbstractAction
{
    /**
     * @Inject
     * @var IndexLogic
     */
    protected $indexLogic;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workContact/export", methods="GET")
     */
    public function handle()
    {
        $corpId = user()['corpIds'];
        if (count($corpId) != 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请先选择企业');
        }

        // 接收参数
        $params = $this->request->inputs(
            [
                'keyWords', 'remark', 'fieldId', 'fieldType', 'fieldValue', 'gender', 'addWay', 'roomId', 'groupNum',
                'employeeId', 'startTime', 'endTime', 'businessNo', 'page', 'perPage', 'tags', 'lossStatus', 'type', 'fieldList',
                'bindingType',
            ],
            [
                'page' => 1, 'perPage' => 10000000000, 'type' => 1,
            ]
        );
       $list= $this->indexLogic->handle($params);
        return $this->processingToTal($list['list']??[]);
    }
    /**
     * 组装基础数据
     * @param $tags
     * @return array
     */
    private function processingToTal($tags): array
    {
        $url = '';
        if (!empty($tags)) {
            $newExcel = new Spreadsheet();  //创建一个新的excel文档
            $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
            $objSheet->setTitle('企微备注');  //设置当前sheet的标题

            //设置宽度为true,不然太窄了
            $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);

            //设置第一栏的标题
            $objSheet->setCellValue('A1', '联系人')
                ->setCellValue('B1', '联系人备注')
                ->setCellValue('C1', '关联客户')
                ->setCellValue('D1', '所属客服')
                ->setCellValue('E1', '客服所属部门')
                ->setCellValue('F1', '标签')
                ->setCellValue('G1', '流失状态')
                ->setCellValue('H1', '添加时间')
                ->setCellValue('I1', '添加渠道');

            //第二行起，每一行的值,setCellValueExplicit是用来导出文本格式的。

            //->setCellValueExplicit('C' . $k, $val['admin_password']PHPExcel_Cell_DataType::TYPE_STRING),可以用来导出数字不变格式
            foreach ($tags as $k => $tag) {
                $k = $k + 2;
                $objSheet->setCellValue('A' . $k, $tag['name'])
                    ->setCellValue('B' . $k, $tag['remark'])
                    ->setCellValue('C' . $k, $tag['clientNames'])
                    ->setCellValue('D' . $k, is_array($tag['employeeName'])?implode(',',$tag['employeeName']):$tag['employeeName'])
                    ->setCellValue('E' . $k, implode(',', $tag['departmentName']))
                    ->setCellValue('F' . $k, implode(',', $tag['tag']))
                    ->setCellValue('G' . $k, is_numeric($tag['status'])?($tag['status'] == 1 ? '正常' : ($tag['status'] == 2 ? '删除' : '拉黑')):'')
                    ->setCellValue('H' . $k, $tag['createTime'])
                    ->setCellValue('I' . $k, $tag['addWayText']);
            }
            $url = $this->downloadExcel($newExcel, '企微备注', 'Xlsx');
        }
        return ['url' => $url];
    }

    //公共文件，用来传入xls并下载
    public function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

//        $objWriter->save('php://output');
        //通过php保存在本地的时候需要用到
        $url = BASE_PATH . '/storage/upload/static' . '/企微备注.xlsx';
        $objWriter->save($url);
        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        //If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        return 'http://manage-cop.sczrk.cn/api/static/企微备注.xlsx';
    }

}
